<?php

class Sistema_GaleriaController extends App_Controller_Action
{
    private $_table     = 'GALERIA';
    private $_pk        = 'GAL_ID';
    private $_order_col = 'GAL_ORD';
    private $_order     = 'ASC';
    //private $_sta_col   = 'GAL_STA';
    private $obj        = '';
    public $dir = 'public/upload/galeria/';
    
    private $tam11 = '280';//'200';
    private $tam12 = '280';//'200';

    private $tam21 = '280';//'200';
    private $tam22 = '560';//'400';

    private $tam31 = '560';//'400';
    private $tam32 = '280';//'200';

    private $tam41 = '560';//'400';
    private $tam42 = '560';//'400';
    
    public function init()
    {
        $this->obj = new Sistema_Model_DbTable_Galeria();
    }

    public function indexAction() {
        
        $modulo = $this->_getParam('modulo','galeria');
        $prt_id = $this->_getParam('prt_id',0);
        
        $this->view->prt_id = $prt_id;
        
        if(strlen($modulo) > 2){ 
            $this->dir = 'public/upload/'.$modulo.'/';
            $amb_id = $this->_getParam('amb_id',0);
            $this->view->link = $this->_urlbase.'/'.$this->_modulo.'/'.$modulo.'/index/amb_id/'.$amb_id;
            $this->view->link_nom = 'Voltar aos Projetos';
        }
        else{
            $this->view->link_nom = 'Voltar';
        }
        
       
        
        $this->view->dir = $this->dir;
        
        // variaveis de sessão para multiupload
        $_SESSION['dir_url'] = $_SERVER['DOCUMENT_ROOT'].$this->_urlbase.'/';
        $_SESSION['dir_uploud'] = $_SESSION['dir_url'].$this->dir;
        $_SESSION['img_width'] = $this->tam11;
        $_SESSION['img_height'] = $this->tam12;
        $_SESSION['insert'] = $modulo;
        $_SESSION['img_mod'] = $modulo; 
        $_SESSION['img_id'] = $prt_id;
        
        if($modulo  == 'demarto'){ // 280x280
            $_SESSION['img_width'] = $this->tam11;
            $_SESSION['img_height'] = $this->tam12;
        }
        
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_galeria.js?12=13');
        
        Zend_Loader::loadClass('imagem','library');
        
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            //if(is_uploaded_file($_FILES['imagem'])) {
                
                $id = (int) $this->_getParam('id',0);
                
                $returnImg = imagem::upload('imagem',$this->dir,$id,TRUE,$this->tam11,$this->tam12);
                
                $data = array(
                    'GAL_ID'    => $id,
                    'GAL_NOM'   => $this->_getParam('titulo'),
                    'GAL_ORD'   => $this->_getParam('tamanho'),
                    'GAL_MOD'   => $modulo,
                    'GAL_MODNUM' => $prt_id,
                );
                
                if ($id == 0){
                    $this->obj->insert($data);
                    $id =  $this->obj->getAdapter()->lastInsertId();                    
                    imagem::rename($id,$this->dir,$returnImg['filenew'],TRUE);
                }
           //} 
        }
        
        //$this->view->result = $this->obj->fetchAll($this->obj->select()->order('GAL_ORD ASC'));
        
        $where = $this->_pk . ' > 0';
        
        $where .= ' AND GAL_MOD LIKE "'.$modulo.'"';
        $where .= ' AND GAL_MODNUM = '.$prt_id;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $result;
        
    }
    
    
    public function editAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        $html = '';
        $id = '';
        
        $modulo = $this->_getParam('modulo',0);
        $prt_id = $this->_getParam('prt_id',0);
        
        try{
            if($this->getRequest()->isPost()) {

                $id = $this->_getParam('id');
                $tam = $this->_getParam('tamanho') == 'N' ? 'D':'N'; // inverte
                
                $src = $id;
                $id = (int) str_replace('_g','', $id);
                
                
                $data = array(
                    'GAL_ID'    => $id,
                    'GAL_NOM'   => $this->_getParam('titulo',''),
                    'GAL_TAM'   => $tam,
                    'GAL_MOD'   => $modulo,
                    'GAL_MODNUM' => $prt_id,
                );

                $gal = $this->obj->fetchRow($this->_pk.' = ' . $id);

                if($gal[$this->_pk] > 0)
                    $this->obj->update($data, $this->_pk.' = ' . $id);
                else $this->obj->insert($data); 


                Zend_Loader::loadClass('imagem','library');

                foreach(glob($this->dir.$src.'_tb.*') as $file) $filenewp = $file;

                foreach(glob($this->dir.$src.'.*') as $file) $filename = $file;

                $tam_img = getimagesize($filenewp);
                $tam = $tam_img[0];

                $row = $this->obj->fetchRow('GAL_ID = ' . $id);

                $html =  $this->view->partial('galeria/img.phtml', array('urlbase' => $this->_urlbase, 'controller' => $this->_controller,'id'=>$id));           


            }else {           

                //$id = $this->_getParam('id');

                //$result = $this->obj->fetchRow('GAL_ID = '.$id);

               /// $html =  $this->view->partial('galeria/edit.phtml', array('urlbase' => $this->_urlbase, 'controller' => $this->_controller,'result'=>$result));           

            }
        } catch(Exception $ex) {
            echo '<script>alert("'.$ex->getMessage().'");</script>';
            exit();
        }
        echo json_encode(array('ok' => true, 'html' => $html, 'id' => $id));
    
    }

    public function deleteAction() {
        
        if(strlen($_SESSION['img_mod']) > 2) $this->dir = 'public/upload/'.$_SESSION['img_mod'].'/';
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  

        $ok = FALSE;
        
        $id = $this->_getParam('id', 0);
        $src = $this->_getParam('src', '');
        
        try{
            if(strlen($id) > 0 ) {

                $temp = explode('.', $id);
                $img = str_replace('_tb', '', $temp[0]); // 1_g_6_tb
                
                $where = 'GAL_IDIMG like "%'.$id.'%" AND GAL_MOD like "%'.$_SESSION['img_mod'].'%"';
                $ok = (bool) $this->obj->delete($where);
                
                //$ok = (bool) $this->obj->delete('GAL_ID = '.$id);
                //$ok = (bool) $this->obj->delete('GAL_NOM like "'.$src.'"'); 

                // deletas demais imagens
                foreach (glob($this->dir.$id.'*.*') as $file) {

                    $temp = str_replace('_tb', '', $file);

                    @unlink(str_replace('_g', '',$temp));
                    @unlink(str_replace('_g', '_m',$temp));
                    @unlink(str_replace('_g', '_f',$temp));
                    @unlink($temp);
                }
                @unlink($file);
                
                $ok = true;
            }
        } catch(Exception $ex) {
            echo $ex->getMessage();
        }
        
        echo json_encode(array('ok' => $ok));
    }
    public function ordemAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $id = $this->_getParam('id',0);
        $src = $id;
        //$id = (int) str_replace('_g','', $id);
        $ord = (int) $this->_getParam('ordem',0);
        
        //foreach(glob($this->dir.$id.'_tb.*') as $file) $img = $file;
        
        //print_r($data);
        //$row = $this->obj->fetchRow($this->_pk.' = '.$id);
        $row = $this->obj->fetchRow('GAL_IDIMG like "%'.$id.'%"');
        
        if($row[$this->_pk] > 0)
        {  
            $data = array(
                'GAL_ORD'   => $ord,
            );
            $this->obj->update($data, 'GAL_IDIMG like "%'.$id.'%"');
        }else{
            $data = array(
                'GAL_NOM'   => '',
                'GAL_ORD'   => $ord,
                'GAL_MOD'   => $_SESSION['img_mod'],
                'GAL_IDIMG' => $id,
                'GAL_MODNUM'=> $_SESSION['img_id'],
            );
            $this->obj->insert($data);
        }
                
        echo json_encode(array('ok' => TRUE));
    }
    
    public function tamanhoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        $html = '';
        $id = '';
        
        $id = $this->_getParam('id');
        $tam = $this->_getParam('tam'); // inverte

        $src = $id;
        $id = (int) str_replace('_g','', $id);
        
        Zend_Loader::loadClass('imagem','library');

        foreach(glob($this->dir.$src.'_tb.*') as $file) $filenewp = $file;

        foreach(glob($this->dir.$src.'.*') as $file) $filename = $file;
        
        try{
            
            if($tam == '1') imagem::reize($filename,$filenewp, $this->tam11, $this->tam12);
            else if($tam == '2') imagem::reize($filename,$filenewp,$this->tam21,$this->tam22);
            else if($tam == '3') imagem::reize($filename,$filenewp,$this->tam31,$this->tam32);
            else if($tam == '4') imagem::reize($filename,$filenewp,$this->tam41,$this->tam42);
            
        } catch(Exception $ex) {
          echo '<script>alert("'.$ex->getMessage().'");</script>';
          exit();
        }   
        /*
        try{
            if($this->getRequest()->isPost()) {

                $id = $this->_getParam('id');
                $tam = $this->_getParam('tamanho') == 'N' ? 'D':'N'; // inverte
                
                $src = $id;
                $id = (int) str_replace('_g','', $id);
                
                
                $data = array(
                    'GAL_ID'    => $id,
                    'GAL_NOM'   => $this->_getParam('titulo',''),
                    'GAL_TAM'   => $tam,
                );

                $gal = $this->obj->fetchRow($this->_pk.' = ' . $id);

                if($gal[$this->_pk] > 0)
                    $this->obj->update($data, $this->_pk.' = ' . $id);
                else $this->obj->insert($data); 


                $row = $this->obj->fetchRow('GAL_ID = ' . $id);

                $html =  $this->view->partial('galeria/img.phtml', array('urlbase' => $this->_urlbase, 'controller' => $this->_controller,'id'=>$id));           


            }else {           

                //$id = $this->_getParam('id');

                //$result = $this->obj->fetchRow('GAL_ID = '.$id);

               /// $html =  $this->view->partial('galeria/edit.phtml', array('urlbase' => $this->_urlbase, 'controller' => $this->_controller,'result'=>$result));           

            }
        } catch(Exception $ex) {
            echo '<script>alert("'.$ex->getMessage().'");</script>';
            exit();
        }
         
        */
        
        echo json_encode(array('ok' => true, 'html' => $html, 'id' => $id));
    
    }
    
    public function descricaoAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $id = $this->_getParam('id',0);
        $src = $id;
        //$id = (int) str_replace('_g','', $id);
        $desc = $this->_getParam('desc','');
        $ok = FALSE;
        
        //$row = $this->obj->fetchRow('GAL_IDIMG like "%'.$id.'%"');
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE GAL_IDIMG like "%'.$id.'%"';
        $row = $this->db->fetchRow($query);
        
        if($row[$this->_pk] > 0)
        {  
            $data = array(
                'GAL_DSC'   => $desc,
            );
            $ok = (bool) $this->obj->update($data, 'GAL_IDIMG like "%'.$id.'%"');
        }
                
        echo json_encode(array('ok' => $ok));
    }
    
}



